package com.hj.authority.feign.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hj.security.domain.constant.SecurityConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * @author hj
 * @Date 2023/5/20
 * @Description:
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        /*
         * 获取原线程的request对象的请求头中的 Authorization 或者 请求参数中的 access_token
         * RequestContextHolder.getRequestAttributes():获取request原始的请求头对象
         * 接口类RequestAttributes不能使用,所以强转为ServletRequestAttributes类型
         */
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttributes) {
            return;
        }
        //获取原Request对象
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //把原request的请求头的所有参数都拿出来
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            //获取每个请求头参数的名字
            String name = headerNames.nextElement();
            // 跳过 Content-Length 大小写都会存在 content-length 否则post请求 @RequestBody
            // 报错 too many bytes written executing POST
            if ("Content-Length".equalsIgnoreCase(name)) {
                continue;
            }
            // 获取值
            String value = request.getHeader(name);
            // 放到feign调用对象的request中去
            requestTemplate.header(name, value);
        }
        // 可能token是放在请求参数里面,也取出来放进去~
        String s = request.getParameter(SecurityConstant.ACCESS_TOKEN);
        if (StrUtil.isNotBlank(s)) {
            requestTemplate.query(SecurityConstant.ACCESS_TOKEN, s);
        }
    }


}
